package iris_controller

import (
	"github.com/kataras/iris/v12"
	"gluenet/internal/glue-srvp/domain"
	"gluenet/internal/pkg/infra"
	"gluenet/internal/pkg/infra/prepare"
)

func init() {
	prepare.RegisterAuthController(func() {
		controller := NewAgentController()
		prepare.InjectAuthController(func() *Agent {
			return controller
		})
	})
}

type Agent struct {
	Agent *domain.Agent
}

func NewAgentController() *Agent {
	r := &Agent{}
	prepare.FetchDependency(&r.Agent)
	return r
}

// Get serves
// Method:   GET
// Resource: http://localhost:8080/apis/agent/runtime/all
func (c *Agent) GetRuntimeAll(ctx iris.Context) *infra.Response {
	organizeId := int64(100)
	objs, err := c.Agent.Runtime(organizeId)
	if err != nil {
		return infra.ResponseReqErr(err, nil)
	}
	return infra.ResponseOK(objs)
}

// Get serves
// Method:   GET
// Resource: http://localhost:8080/apis/agent/runtime/childinfo
func (c *Agent) GetRuntimeChildinfo(ctx iris.Context) *infra.Response {
	objs, err := c.Agent.RuntimeChild(100)
	if err != nil {
		return infra.ResponseReqErr(err, nil)
	}
	return infra.ResponseOK(objs)
}

// Get serves
// Method:   GET
// Resource: http://localhost:8080/apis/agent/all
func (c *Agent) GetAll(ctx iris.Context) *infra.Response {
	objs, err := c.Agent.FindAll()
	if err != nil {
		return infra.ResponseReqErr(err, nil)
	}
	return infra.ResponseOK(objs)
}

// Get serves
// Method:   GET
// Resource: http://localhost:8080/apis/agent/cluster
func (c *Agent) GetCluster(ctx iris.Context) *infra.Response {
	objs, err := c.Agent.FindClusters()
	if err != nil {
		return infra.ResponseReqErr(err, nil)
	}
	return infra.ResponseOK(objs)
}

func (c *Agent) GetUpdateNode(ctx iris.Context) *infra.Response {
	var auth = infra.AuthInfo{}
	auth.UserId = ctx.Values().GetString("user_id")
	auth.GroupId, _ = ctx.Values().GetInt64("group_id")
	auth.AuthLevel, _ = ctx.Values().GetInt64("auth_level")

	err := c.Agent.UpdateNodes(auth)
	if err != nil {
		return infra.ResponseReqErr(err, nil)
	}
	return infra.ResponseOK(nil)
}
